import { get, post } from '@/utils/axios'
import { filterUploadList } from '@/utils/filterData'

export default {
  props: ['title', 'dialogVisible', 'formId'],
  data() {
    return {
      form: {},
      beforeRes: {},
      beforeId: null,
      isAdd: true,
      loading: true,
      removeIds: [],
      fileList: [],
      compRefs: {}
    }
  },
  methods: {
    /**
     * 通用的提示封装
     */
    submitSuccessNotify() {
      this.$notify({
        title: '提交成功',
        type: 'success',
        duration: 2500
      })
      this.handleBeforeCloseDialog()
      this.closeCurrentDialog()
    },
    addSuccessNotify() {
      this.$notify({
        title: '新增成功',
        type: 'success',
        duration: 2500
      })
      this.handleBeforeCloseDialog()
      this.closeCurrentDialog()
    },
    editSuccessNotify() {
      this.$notify({
        title: '编辑成功',
        type: 'success',
        duration: 2500
      })
      this.handleBeforeCloseDialog()
      this.closeCurrentDialog()
    },
    validFormNotify(message) {
      const h = this.$createElement
      const errorMsg = h('ul', [...message.map((item) => h('li', item))])
      this.$notify({
        title: '表单有误',
        type: 'warning',
        message: errorMsg,
        duration: 0
      })
    },
    notify(title, type) {
      this.$notify({
        title: title,
        type: type,
        duration: 2500
      })
    },
    // 关闭当前弹窗
    closeCurrentDialog() {
      this.handleClearComp()
      this.clearValid()
      this.$parent.handleCanleDialog()
    },
    async showDialog() {
      this.beforeShowDialog()
      const formId = this.formId
      // fix refs not found
      if (!Object.keys(this.compRefs).length) {
        this.compRefs = this.$refs
      }
      // form值制为空
      this.isAdd = formId.length === 0
      // 防止再次请求
      if (this.beforeId || formId) {
        if (formId === this.beforeId) {
          // 深拷贝防止多次请求相同数据
          const beforeRes = this._.cloneDeep(this.beforeRes)
          const { formFileList, form } = beforeRes
          this.form = form
          this.handleSetFiles(formFileList)
          this.fillFormAfter(beforeRes)
        } else {
          if (!this.isAdd) {
            await get(this.apiUrl.get, { formId }).then((res) => {
              const { formFileList, form } = this._.cloneDeep(res.obj)
              this.beforeRes = this._.cloneDeep(res.obj)
              this.beforeId = formId
              this.form = form
              this.handleSetFiles(formFileList)
              this.fillFormAfter(res)
            })
          }
        }
      }
      this.loading = false
    },
    // 附件 富文本数据挂载后处理
    fillFormAfter() {},
    handleSaveForm() {
      this.beforeSaveForm()
      // 表单校验
      this.$refs['formValid'].validate((valid) => {
        if (valid) {
          const fileList = this.fileList
            .reduce((all, next) => all.some((item) => item['fileId'] === next['fileId']) ? all : [...all, next], [])

          const removeIds = [...new Set(this.removeIds)]
          // 附件
          if (removeIds.length) {
            this.form.fileRemoveIds = removeIds
          }
          if (fileList.length) {
            this.form.newFileList = fileList
          }

          post(this.apiUrl.save, this.form, false).then((res) => {
            this.handleResultOper(res)
          })
        } else {
          this.$children[0].disabled = false
          this.notify('请确认表格填写规则', 'error')
          return false
        }
      })
    },
    handleCloseDialog() {
      this.loading = true
      this.handleClearComp()
      this.clearValid()
      this.handleBeforeCloseDialog()
      this.$emit('close')
    },
    handleBeforeCloseDialog() {},
    beforeSaveForm() {},
    // 提交成功后处理
    handleResultOper(result) {
      const resFlag = result.state
      this.loading = resFlag
      if (resFlag) {
        // 修改后数据变化 需重新请求
        this.beforeId = null
        this.isAdd ? this.addSuccessNotify() : this.editSuccessNotify()
      } else {
        this.$children[0].disabled = false
        const errMsg = result.obj
        errMsg instanceof Array ? this.validFormNotify(errMsg) : this.notify(errMsg, 'error')
      }
    },
    getFile({ newFileList, removeIds }) {
      if (newFileList.length) {
        this.fileList.push(...newFileList)
      }
      if (removeIds.length) {
        this.removeIds.push(...removeIds)
      }
    },
    handleSetFiles(formFileList) {
      const fileList = filterUploadList(formFileList)
      const refs = this.compRefs
      for (const ref in refs) {
        if (ref.indexOf('file') >= 0) {
          const upload = refs[ref]
          const processId = upload.processId
          upload.handleSetFileList(fileList[processId] || [])
        }
      }
    },
    // 清除组件内容
    handleClearComp() {
      const compRefs = this.compRefs
      for (const ref in this.compRefs) {
        const upload = compRefs[ref]
        // 附件
        if (ref.indexOf('file') >= 0) {
          upload.handleClearFileList()
          continue
        }
      }
    },
    clearValid() {
      const formValid = this.$refs['formValid']
      if (formValid) {
        this.$nextTick(() => {
          formValid.clearValidate()
        })
      }
    },
    beforeShowDialog() {},
    // 清除表单项
    clearForm() {
      // 清除附件
      this.fileList = []
      this.removeIds = []
      // 清除表单
      this.form = Object.create(null)
    }
  }
}
